package com.MutiModule.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 通过静态内部类实现 单例模型 满足线程安全
 * 
 * @author alexgaoyh
 * 
 */
public class PropertiesUtilss {

	/**
	 * 從fileUrl文件中，讀取keyName對應的value值
	 * 
	 * @param fileUrl
	 *            配置文件文件路徑
	 * @param keyName
	 *            配置文件中讀取的key名稱
	 * @return
	 */
	public static Object getProperties(String fileUrl, String keyName) {
		Properties prop = new Properties();
		InputStream in = PropertiesUtilss.class.getClassLoader().getResourceAsStream(fileUrl);
		try {
			if(in != null) {
				prop.load(in);
				return prop.getProperty(keyName);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 通过 filename 获取 Properties 
	 * @param filename
	 * @return
	 */
	public static Properties readPropertiesFileAsMap(String filename) {
		Properties properties = new Properties();
		try {
			properties.load(PropertiesUtilss.class.getResourceAsStream(filename));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return properties;
	}
	
	/**
	 * 通过 filename 路径（properties文件），获取到配置文件项的map集合
	 * @param filename
	 * @return
	 */
	public static Map<String, String> getMapByProperties(String filename) {
		
		Properties properties = readPropertiesFileAsMap(filename);
		
		Map<String, String> returnMap = new HashMap<String, String>();
		Set<Object> keys = properties.keySet();// 返回属性key的集合
		for (Object key : keys) {
			returnMap.put(key.toString(), properties.get(key).toString());
		}
		
		return returnMap;
	}
}
